import { initInfo } from "./log";
import abilityAccessCtrl from '@ohos.abilityAccessCtrl'
import bundle from '@ohos.bundle'
interface userGrantPermissionParam{
    permissions: any[],
    bundleName?: string,
    bundleFlag?: number,
    userID?: number,
}
let log = initInfo('UserGrantPermission');
export async function userGrantPermission(context:any, opts:userGrantPermissionParam, call?:Function){
    //    log(`start`)
    let {
        permissions = [],
        bundleName = "",
        bundleFlag = 0, // 数字枚举
        userID = 100, // 系统设置默认100
    } = opts;
    if(!bundleName){
        bundleName = context.abilityInfo.bundleName
    }
    //    log(`bundleName: ${bundleName}`)
    var tokenID: any = undefined;
    // 获取应用信息
    var appInfo = await bundle.getApplicationInfo(bundleName, bundleFlag, userID);

    tokenID = appInfo.accessTokenId;
    //    log(`User_Grant tokenID: ${tokenID}`)
    var atManager = abilityAccessCtrl.createAtManager();

    let noPermissions: string[] = []
    await Promise.all(permissions.map(async (permission) => {
        // 检验权限是否已授权
        let result = await atManager.verifyAccessToken(tokenID, permission.name);
        //        log(`${permission.name} res ${result}`)
        if (result == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) {
            //            log(`${permission.name} is authorized`);
        } else {
            noPermissions.push(permission.name)
        }
    }));
    //    log(`noPermissions: ${JSON.stringify(noPermissions)}`)
    // 申请动态授权，使用接口：requestPermissionsFromUser
    let res = await context.requestPermissionsFromUser(noPermissions);
    //    console.log(`requestPermissionsFromUser res ${JSON.stringify(res)}`);
    //    let requestSuccess = true;
    if(res && res.authResults){
        res.authResults.forEach((r,i)=>{
            if(r == 0){
                //                log(`${noPermissions[i]} success!`)
            } else if (r == -1) {
                //                requestSuccess = false;
                log(`${noPermissions[i]} faild!`)
            }
        })
    } else {
        log(`faild!`)
    }
    //    log(`end`)
    if(call){
        call();
    }
}
